<?php
/**
 * @Author: rocky
 * Date: 2020/1/20
 * Time: 15:36
 */


namespace app\shop\controller\api\v2;


use app\common\controller\BaseApiController;
use app\common\facade\Token;
use app\common\model\Account;
use app\common\service\Sms;
use app\shop\model\ShopWithdrawal;
use think\Db;

/**
 * 提现
 * Class Withdrawal
 * @package app\shop\controller\api\v2
 */
class Withdrawal extends BaseApiController
{
    /*
     * 申请提现页面
     */
    public function getinfo()
    {
        //提现手续费比例
        $data['service_rate'] = sysconf('withdrawal_service_rate');
        $data['money'] = Token::user()->money;
        $data['phone'] = Token::user()->phone;
        $this->successCode($data);
    }

    /*
     * 申请提现
     */
    public function postInfo()
    {
        //申请提现金额
        $money = $this->request->post('money');
        //手机验证码
        $code = $this->request->post('code');
        $user = Token::user();
        if ($money <= 0) $this->errorCode(100, '提现金额错误');
        if ($money > $user->money) $this->errorCode(100, '提现金额大于可提现金额');
        if (!Sms::check($user->phone, $code, 3)) {
            //提现手续费比例
            $service_rate = sysconf('withdrawal_service_rate');
            $service_money = 0;
            if ($service_rate > 0) {
                $div = bcdiv($service_rate, 100, 2);
                $service_money = bcmul($money, $div, 2);
            }
            //钱包账单操作
            $res = Account::recordMoney($money,Token::id(),'申请提现',1,"申请提现 ￥{$money}");
            if($res){
                //提现申请创建
                ShopWithdrawal::create([
                    'withdrawal_money' => $money,
                    'money' => $money - $service_money,
                    'service_money' => $service_money,
                    'uid' => Token::id()
                ]);
                $this->successCode();
            }else{
                $this->errorCode();
            }
        } else {
            $this->errorCode(4003);
        }
    }
    /*
     * 提现记录
     */
    public function postList(){
        $data = ShopWithdrawal::uid()->field("'提现' as title,money,action_time")->where('status',2)->pages()->select();
        $this->successCode($data);
    }
}